package demoMod.gdxform.ui;

import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.graphics.Color;
import com.badlogic.gdx.graphics.g2d.SpriteBatch;
import demoMod.gdxform.abstracts.ScrollBar;

public class GHScrollBar extends ScrollBar {
    public GHScrollBar(float x, float y, float width, float height) {
        super(x, y, width, height);
    }

    @Override
    public void render(SpriteBatch sb) {
        if (!this.visible()) return;
        sb.setColor(Color.WHITE.cpy());
        if (this.bgTexture != null) {
            sb.draw(this.bgTexture, getX(true), getY(true), getWidth(), getHeight());
        }
        if (this.barTexture != null) {
            sb.draw(this.barTexture, getX(true) + (getWidth() - getBarLength()) * getProgress(),
                    getY(true), getBarLength(), getHeight());
        }
    }

    @Override
    public float getX(boolean isAbsolute) {
        if (getParent() instanceof GScrollPane) {
            return getParent().getX(isAbsolute);
        }
        return super.getX(isAbsolute);
    }

    @Override
    public float getY(boolean isAbsolute) {
        if (getParent() instanceof GScrollPane) {
            return getParent().getY(isAbsolute);
        }
        return super.getY(isAbsolute);
    }

    @Override
    public float getWidth() {
        if (getParent() instanceof GScrollPane) {
            return getParent().getWidth() - getHeight();
        }
        return super.getWidth();
    }

    @Override
    public float getHeight() {
        return super.getHeight();
    }

    @Override
    protected void checkBarLength(float barLength) {
        if (barLength > getWidth()) {
            throw new IllegalArgumentException("barLength must less than width. barLength: " + barLength + ", width: " + getWidth());
        }
    }

    @Override
    public boolean mouseDragged(int screenX, int screenY) {
        if (mouseDown) {
            if (getWidth() - getBarLength() != 0) {
                float delta = Gdx.input.getDeltaX() / (getWidth() - getBarLength());
                float mul = delta > 0 ? 1.0F : -1.0F;
                delta = (int) (delta * 100) / 100.0F;
                if (Math.abs(delta) == 0) {
                    delta = mul * 0.01F;
                }
                float progress = getProgress() + delta;
                setProgress(progress);
            }
            return true;
        }
        return false;
    }
}
